package com.aeye.mbr.common.util;

import com.aeye.mbr.common.db.KeyInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/4/2.
 */
public class SequenceUtils {
    private Map<String, KeyInfo> keyMap = new HashMap<String, KeyInfo>(20); //Sequence载体容器
    private static final int POOL_SIZE = 10;      //Sequence值缓存大小

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 获取下一个Sequence键值
     * @param keyName Sequence名称
     * @return 下一个Sequence键值
     */
    public synchronized long getNextKeyValue(String keyName) {
        KeyInfo keyInfo = null;
        Long keyObject = null;
        try {
            if (keyMap.containsKey(keyName)) {
                keyInfo = keyMap.get(keyName);
            } else {
                keyInfo = new KeyInfo(keyName, POOL_SIZE,jdbcTemplate);
                keyMap.put(keyName, keyInfo);
            }
            keyObject = keyInfo.getNextKey();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return keyObject;
    }
}
